package com.wjk.kylin.id.core.worker;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.wjk.kylin.id.core.dto.BaseOutDTO;
import com.wjk.kylin.id.core.dto.WorkerIdDTO;
import com.wjk.kylin.id.core.exception.UidGenerateException;
import com.wjk.kylin.id.core.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 根据bizType 生成 workerId
 * workerId 每次启动自增
 *
 * @author wjk
 */
public class DefaultWorkerIdAssigner implements WorkerIdAssigner {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWorkerIdAssigner.class);

    private static final List<String> SERVER_LIST = new ArrayList<>();
    private final String params;
    private static final String URL = "http://{0}/kylin-id/uid/worker/id";

    /**
     * @param bizType biz_type 业务标识 用于获取 worker id
     * @param servers 发号器服务地址 获取 worker id 地址
     */
    public DefaultWorkerIdAssigner(String bizType, List<String> servers) {
        Assert.notEmpty(servers, "servers must have at least one");
        Assert.hasText(bizType, "bizType must be not blank");

        //
        params = "{\"bizType\":\"" + bizType + "\"}";
        for (String server : servers) {
            String url = MessageFormat.format(URL, server);
            SERVER_LIST.add(url);
        }
    }

    /**
     * http请求查询workerId
     *
     * @return
     */
    @Override
    public long assignWorkerId() {

        Long workerId = getWorkerId();
        if (workerId == null) {
            LOGGER.error("error query workerId ,{}", params);

            throw new UidGenerateException("error query workerId,params:" + params);
        }

        return workerId;
    }

    /**
     * http请求查询workerId
     *
     * @return
     */
    public Long getWorkerId() {
        String url = this.chooseService();
        long startTime = System.currentTimeMillis();
        String response = HttpUtil.doPost(url, this.params);
        LOGGER.info("kylin-id client getWorkerId end,url:{}, request:{},response:{},耗时{}ms", url, this.params, response, System.currentTimeMillis() - startTime);
        if (StringUtils.isBlank(response)) {
            return null;
        }
        BaseOutDTO<WorkerIdDTO> outDTO = JSON.parseObject(response, new TypeReference<BaseOutDTO<WorkerIdDTO>>() {
        });
        if (outDTO == null) {
            return null;
        }
        if (outDTO.getCode() != 200) {
            LOGGER.error("kylin-id client getWorkerId end,url:{}, request:{},response:{}", url, this.params, response);
            return null;
        }
        WorkerIdDTO data = outDTO.getData();
        if (data == null) {
            LOGGER.error("kylin-id client getWorkerId end,url:{}, request:{},response:{}", url, this.params, response);
            return null;
        }
        Long workerId = data.getWorkerId();
        if (workerId == null) {
            LOGGER.error("kylin-id client getWorkerId end,url:{}, request:{},response:{}", url, this.params, response);
            return null;
        }

        return workerId;
    }

    /**
     * 随机获取mes服务地址
     *
     * @return
     */
    private String chooseService() {
        if (CollectionUtils.isEmpty(SERVER_LIST)) {
            throw new NullPointerException("server is null");
        }
        String url = "";
        if (SERVER_LIST.size() == 1) {
            url = SERVER_LIST.get(0);
        } else if (SERVER_LIST.size() > 1) {
            url = SERVER_LIST.get(new Random().nextInt(SERVER_LIST.size()));
        }
        return url;
    }

}
